// app/middleware/logging.js
module.exports = () => {
  return async (ctx, next) => {
    // 记录请求开始时间
    const startTime = Date.now();
    // 记录请求入参
    const requestParams = {
      method: ctx.method,
      url: ctx.url,
      headers: ctx.headers,
      body: ctx.request.body,
      query: ctx.query
    };

    const urlList = [
      '/api/logs',
      '/api/person/list',
      '/api/department/list',
      '/api/projectGroup/list',
      '/api/scoringRule/list',
      '/api/contribution/list',
      '/api/contributionData/getPendingDataList',
      '/api/person/getAllContributionStats'
    ];

    try {
      // 执行后续中间件和控制器
      await next();

      if (!(urlList.includes(ctx.url))) {
        // 记录响应返回参数
        const responseParams = {
          status: ctx.status,
          body: ctx.body
        };

        // 记录请求结束时间
        const endTime = Date.now();
        const duration = endTime - startTime;

        // 获取 auth 中间件保存的用户信息
        const user = ctx.state.user || {};

        const __response_body = JSON.stringify(responseParams.body);

        // 获取客户端 IP 地址
        const clientIp = ctx.ip;

        // 插入日志记录到数据库
        const logData = {
          method: requestParams.method,
          url: requestParams.url,
          request_headers: JSON.stringify(requestParams.headers),
          request_body: JSON.stringify(requestParams.body),
          request_query: JSON.stringify(requestParams.query),
          response_status: responseParams.status,
          response_body: __response_body.length <= 1000 ? __response_body : `{'响应内容过长'}`,
          duration,
          user_info: JSON.stringify(user),
          client_ip: clientIp // 添加客户端 IP 到日志数据
        };

        await ctx.app.mysql.insert('api_logs', logData);
      }
    } catch (error) {
      // 处理异常
      ctx.logger.error('Error logging API request:', error);
    }
  };
};